<template>
  <div class="dashboard-container">
    <!-- 星空背景 -->
    <StarField 
      v-if="showStarField" 
      class="starfield-background"
      :auto-rotate="true"
      :star-magnitude="4.5"
      :show-constellations="true"
    />
    <!-- 欢迎区域 -->
    <div class="welcome-section">
      <div class="welcome-content">
        <h1 class="welcome-title">🌌 欢迎回来，{{ username }}</h1>
        <p class="welcome-subtitle">开启您的天文探索之旅</p>
        <div class="current-stats">
          <div class="stat-item">
            <div class="stat-icon">📸</div>
            <div class="stat-content">
              <div class="stat-value">{{ photoCount }}</div>
              <div class="stat-label">分析照片</div>
            </div>
          </div>
          <div class="stat-item">
            <div class="stat-icon">📍</div>
            <div class="stat-content">
              <div class="stat-value">{{ locationCount }}</div>
              <div class="stat-label">观测位置</div>
            </div>
          </div>
          <div class="stat-item">
            <div class="stat-icon">✨</div>
            <div class="stat-content">
              <div class="stat-value">{{ favLocation || '未知' }}</div>
              <div class="stat-label">最佳观测点</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 功能卡片区 -->
    <div class="features-section">
      <h2 class="section-title">您的天文工具箱</h2>
      <div class="feature-cards">
        <!-- EXIF解析器卡片 -->
        <div class="feature-card" @click="navigateTo('exif')">
          <div class="card-header">
            <div class="card-icon">🔭</div>
            <h3 class="card-title">EXIF解析器</h3>
          </div>
          <p class="card-description">
            上传天文摄影图片，分析拍摄参数和设备信息，优化您的天文摄影效果
          </p>
          <div class="card-footer">
            <span class="card-cta">开始分析</span>
            <span class="card-arrow">→</span>
          </div>
        </div>

        <!-- 位置检测卡片 -->
        <div class="feature-card" @click="navigateTo('location')">
          <div class="card-header">
            <div class="card-icon">📍</div>
            <h3 class="card-title">位置检测</h3>
          </div>
          <p class="card-description">
            检测您的位置并计算最佳天文观测条件，包括星空可见度、光污染等级等
          </p>
          <div class="card-footer">
            <span class="card-cta">检测位置</span>
            <span class="card-arrow">→</span>
          </div>
        </div>

        <!-- 天文事件日历卡片 -->
        <div class="feature-card" @click="navigateTo('events')">
          <div class="card-header">
            <div class="card-icon">📅</div>
            <h3 class="card-title">天文事件日历</h3>
          </div>
          <p class="card-description">
            查看近期天文事件如流星雨、日月食等，掌握最佳观测时机
          </p>
          <div class="card-footer">
            <span class="card-cta">浏览事件</span>
            <span class="card-arrow">→</span>
          </div>
        </div>
        
        <!-- 通知设置卡片 -->
        <div class="feature-card" @click="navigateTo('notifications')">
          <div class="card-header">
            <div class="card-icon">🔔</div>
            <h3 class="card-title">通知设置</h3>
          </div>
          <p class="card-description">
            管理您的天文事件提醒偏好，设置浏览器通知和邮件提醒
          </p>
          <div class="card-footer">
            <span class="card-cta">配置提醒</span>
            <span class="card-arrow">→</span>
          </div>
        </div>
        
        <!-- 个性化推荐卡片 -->
        <div class="feature-card" @click="navigateTo('preferences')">
          <div class="card-header">
            <div class="card-icon">🌟</div>
            <h3 class="card-title">为您推荐</h3>
          </div>
          <div v-if="recommendedEvents.length > 0" class="recommended-events-preview">
            <div v-for="event in recommendedEvents" :key="event.id" class="recommended-event-item">
              <div class="event-date">{{ formatDate(event.date) }}</div>
              <div class="event-title">{{ event.title }}</div>
            </div>
          </div>
          <div v-else class="no-recommendations">
            <p>设置您的兴趣偏好以获取个性化推荐</p>
          </div>
          <div class="card-footer">
            <span class="card-cta">自定义推荐</span>
            <span class="card-arrow">→</span>
          </div>
        </div>
        
        <!-- 事件分享卡片 -->
        <div class="feature-card" @click="navigateTo('eventShare')">
          <div class="card-header">
            <div class="card-icon">📤</div>
            <h3 class="card-title">事件分享</h3>
          </div>
          <p class="card-description">
            创建观测报告，分享您的天文观测体验和照片
          </p>
          <div class="card-footer">
            <span class="card-cta">开始分享</span>
            <span class="card-arrow">→</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 最近活动区域 -->
    <div class="activity-section">
      <h2 class="section-title">最近活动</h2>
      <div v-if="recentActivities.length > 0" class="activity-list">
        <div v-for="(activity, index) in recentActivities" :key="index" class="activity-item">
          <div class="activity-icon">{{ activity.icon }}</div>
          <div class="activity-content">
            <p class="activity-text">{{ activity.text }}</p>
            <p class="activity-time">{{ activity.time }}</p>
          </div>
        </div>
      </div>
      <div v-else class="no-activity">
        <p>暂无最近活动</p>
      </div>
    </div>

    <!-- 快速访问区域 -->
    <div class="quick-access-section">
      <h2 class="section-title">快速访问</h2>
      <div class="quick-access-buttons">
        <button class="quick-button" @click="resetProgress">
          <span class="button-icon">🔄</span>
          <span>重置数据</span>
        </button>
        <button class="quick-button" @click="exportData">
          <span class="button-icon">📥</span>
          <span>导出数据</span>
        </button>
        <button class="quick-button" @click="settings">
          <span class="button-icon">⚙️</span>
          <span>设置</span>
        </button>
      </div>
    </div>
    
    <!-- 太阳系模型视图 -->
    <div v-if="selectedView === 'planets'" class="planet-system-view">
      <PlanetSystem />
      <button class="back-button" @click="selectedView = 'dashboard'">
        返回仪表盘
      </button>
    </div>
    
    <!-- 天文事件日历视图 -->
    <div v-if="selectedView === 'events'" class="events-view">
      <AstronomyEventCalendar />
      <button class="back-button" @click="selectedView = 'dashboard'">
        返回仪表盘
      </button>
    </div>
    
    <!-- 通知设置视图 -->
    <div v-if="selectedView === 'notifications'" class="notifications-view">
      <button class="back-button" @click="selectedView = 'dashboard'">返回仪表盘</button>
      <NotificationSettings />
    </div>
    
    <!-- 视图切换按钮 -->
    <button 
      v-if="selectedView === 'dashboard'"
      class="view-toggle-button"
      @click="selectedView = 'planets'"
    >
      🌌 探索太阳系
    </button>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import StarField from './StarField.vue'
import PlanetSystem from './PlanetSystem.vue'
import AstronomyEventCalendar from './AstronomyEventCalendar.vue'
import NotificationSettings from './NotificationSettings.vue'
import { getUpcomingEvents } from '../data/astronomicalEvents'

export default {
  name: 'Dashboard',
  components: {
    StarField,
    PlanetSystem,
    AstronomyEventCalendar,
    NotificationSettings
  },
  props: {
    username: {
      type: String,
      default: '天文爱好者'
    }
  },
  emits: ['navigate', 'logout'],
  setup(props, { emit }) {
    // 统计数据
    const photoCount = ref(0)
    const locationCount = ref(0)
    const favLocation = ref('')
    
    // 最近活动
    const recentActivities = ref([])
    
    // 宇宙视图控制
    const showStarField = ref(true)
    const showPlanetSystem = ref(false)
    const selectedView = ref('dashboard') // 'dashboard', 'planets'
    const recommendedEvents = ref([])

    // 导航到指定功能
    const navigateTo = (view) => {
      if (view === 'events') {
        selectedView.value = 'events'
      } else if (view === 'notifications') {
        selectedView.value = 'notifications'
      } else if (view === 'eventShare') {
        emit('navigate', 'eventShare')
      } else {
        emit('navigate', view)
      }
    }

    // 重置进度
    const resetProgress = () => {
      if (confirm('确定要重置所有数据吗？此操作不可恢复。')) {
        photoCount.value = 0
        locationCount.value = 0
        favLocation.value = ''
        recentActivities.value = []
        addActivity('已重置所有数据', '🗑️')
      }
    }

    // 导出数据
    const exportData = () => {
      const data = {
        username: props.username,
        photoCount: photoCount.value,
        locationCount: locationCount.value,
        favLocation: favLocation.value,
        recentActivities: recentActivities.value,
        exportDate: new Date().toISOString()
      }
      
      const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `天文数据_${new Date().toISOString().split('T')[0]}.json`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
      
      addActivity('导出了天文数据', '📥')
    }

    // 设置
    const settings = () => {
      navigateTo('preferences')
    }
    
    // 加载推荐事件
    const loadRecommendedEvents = () => {
      try {
        // 获取用户兴趣标签
        const savedTags = localStorage.getItem('userInterestTags')
        const userTags = savedTags ? JSON.parse(savedTags) : ['高可见度', '推荐观测']
        
        // 获取事件类型优先级
        const savedPriorities = localStorage.getItem('eventTypePriorities')
        const typePriorities = savedPriorities ? JSON.parse(savedPriorities) : {}
        
        // 获取用户经验级别
        const savedExperience = localStorage.getItem('userExperienceLevel')
        const experienceLevel = savedExperience || 'beginner'
        
        // 获取未来30天的事件
        const upcomingEvents = getUpcomingEvents(30)
        
        // 计算每个事件的匹配分数
        const scoredEvents = upcomingEvents.map(event => {
          let score = 0
          
          // 根据标签匹配加分
          event.tags.forEach(tag => {
            if (userTags.includes(tag)) {
              score += 10
            }
          })
          
          // 根据事件类型优先级加分
          const typePriority = typePriorities[event.type] || 3
          score += typePriority * 5
          
          // 根据观测经验调整分数
          if (experienceLevel === 'beginner' && event.tags.includes('高可见度')) {
            score += 8
          }
          
          return { ...event, score }
        })
        
        // 按分数排序并取前3个
        recommendedEvents.value = scoredEvents
          .sort((a, b) => b.score - a.score)
          .slice(0, 3)
      } catch (error) {
        console.error('加载推荐事件失败:', error)
        // 如果加载失败，使用默认推荐
        recommendedEvents.value = []
      }
    }
    
    // 格式化日期
    const formatDate = (dateString) => {
      const date = new Date(dateString)
      return `${date.getMonth() + 1}月${date.getDate()}日`
    }

    // 添加活动记录
    const addActivity = (text, icon) => {
      const now = new Date()
      const time = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`
      
      recentActivities.value.unshift({
        text,
        icon,
        time
      })
      
      // 只保留最近10条活动
      if (recentActivities.value.length > 10) {
        recentActivities.value = recentActivities.value.slice(0, 10)
      }
    }

    // 模拟加载用户数据
    onMounted(() => {
      // 模拟从localStorage或API加载数据
      const savedPhotoCount = localStorage.getItem('photoCount')
      const savedLocationCount = localStorage.getItem('locationCount')
      const savedFavLocation = localStorage.getItem('favLocation')
      const savedActivities = localStorage.getItem('recentActivities')
      
      if (savedPhotoCount) photoCount.value = parseInt(savedPhotoCount)
      if (savedLocationCount) locationCount.value = parseInt(savedLocationCount)
      if (savedFavLocation) favLocation.value = savedFavLocation
      if (savedActivities) recentActivities.value = JSON.parse(savedActivities)
      
      // 添加登录活动
      addActivity('登录成功', '✅')
      
      // 保存数据到localStorage的监听器
      const saveData = () => {
        localStorage.setItem('photoCount', photoCount.value)
        localStorage.setItem('locationCount', locationCount.value)
        localStorage.setItem('favLocation', favLocation.value)
        localStorage.setItem('recentActivities', JSON.stringify(recentActivities.value))
      }
      
      // 监听数据变化
      photoCount.value++ // 模拟一个新的照片分析
      locationCount.value++ // 模拟一个新的位置检测
      favLocation.value = '北京'
      
      // 保存数据
      saveData()
      
      // 加载推荐事件
      loadRecommendedEvents()
    })

    // 监听视图切换
    watch(selectedView, (newView) => {
      if (newView === 'planets') {
        showStarField.value = false
      } else {
        showStarField.value = true
      }
    })

    return {
      photoCount,
      locationCount,
      favLocation,
      recentActivities,
      navigateTo,
      resetProgress,
      exportData,
      settings,
      selectedView,
      showStarField,
      recommendedEvents,
      formatDate
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem 0;
  position: relative;
  min-height: 100vh;
}

/* 星空背景 */
.starfield-background {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
}

/* 太阳系视图 */
.planet-system-view, .events-view {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 100;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 2rem;
    background: linear-gradient(135deg, #0a1128 0%, #121e3e 100%);
  }
  
  .events-view {
    justify-content: flex-start;
  }

/* 返回按钮 */
.back-button {
  position: fixed;
  top: 20px;
  left: 20px;
  padding: 12px 24px;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  z-index: 200;
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
}

.back-button:hover {
  background: rgba(0, 0, 0, 0.9);
  border-color: var(--accent-color);
  transform: translateX(-2px);
}

/* 视图切换按钮 */
.view-toggle-button {
  position: fixed;
  bottom: 40px;
  right: 40px;
  padding: 15px 30px;
  background: linear-gradient(135deg, rgba(85, 136, 255, 0.9), rgba(136, 85, 255, 0.9));
  color: white;
  border: none;
  border-radius: 50px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 600;
  z-index: 10;
  backdrop-filter: blur(10px);
  box-shadow: 0 8px 32px rgba(85, 136, 255, 0.4);
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 10px;
}

.view-toggle-button:hover {
  transform: translateY(-3px) scale(1.05);
  box-shadow: 0 12px 40px rgba(85, 136, 255, 0.6);
}

.view-toggle-button:active {
  transform: translateY(-1px);
}

/* 欢迎区域 */
.welcome-section {
  background: var(--bg-card);
  border-radius: 16px;
  padding: 2rem;
  margin-bottom: 2rem;
  border: 1px solid var(--border-color);
  box-shadow: 0 8px 32px var(--shadow-color);
}

.welcome-title {
  font-size: 2rem;
  font-weight: 700;
  color: var(--text-primary);
  margin: 0 0 0.5rem 0;
}

.welcome-subtitle {
  font-size: 1.125rem;
  color: var(--text-secondary);
  margin: 0 0 1.5rem 0;
}

.current-stats {
  display: flex;
  gap: 1.5rem;
  flex-wrap: wrap;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 1rem;
  background: rgba(85, 136, 255, 0.1);
  padding: 1rem 1.5rem;
  border-radius: 12px;
  border: 1px solid rgba(85, 136, 255, 0.2);
}

.stat-icon {
  font-size: 1.5rem;
}

.stat-content {
  display: flex;
  flex-direction: column;
}

.stat-value {
  font-size: 1.5rem;
  font-weight: 700;
  color: var(--accent-color);
}

.stat-label {
  font-size: 0.875rem;
  color: var(--text-secondary);
}

/* 功能卡片区 */
.features-section {
  margin-bottom: 2rem;
}

.section-title {
  font-size: 1.5rem;
  font-weight: 700;
  color: var(--text-primary);
  margin: 0 0 1.5rem 0;
}

.feature-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 1.5rem;
}

.feature-card {
  background: var(--bg-card);
  border-radius: 16px;
  padding: 2rem;
  border: 1px solid var(--border-color);
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 16px var(--shadow-color);
}

.feature-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 32px var(--shadow-color);
  border-color: var(--accent-color);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin-bottom: 1rem;
}

.card-icon {
  font-size: 2rem;
}

.card-title {
  font-size: 1.25rem;
  font-weight: 700;
  color: var(--text-primary);
  margin: 0;
}

.card-description {
  color: var(--text-secondary);
  margin: 0 0 1.5rem 0;
  line-height: 1.6;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: var(--accent-color);
  font-weight: 500;
}

.card-arrow {
  font-size: 1.25rem;
  transition: transform 0.3s ease;
}

.feature-card:hover .card-arrow {
  transform: translateX(5px);
}

/* 最近活动区域 */
.activity-section {
  background: var(--bg-card);
  border-radius: 16px;
  padding: 2rem;
  margin-bottom: 2rem;
  border: 1px solid var(--border-color);
}

.activity-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.activity-item {
  display: flex;
  align-items: flex-start;
  gap: 1rem;
  padding: 1rem;
  background: rgba(85, 136, 255, 0.05);
  border-radius: 12px;
  border: 1px solid rgba(85, 136, 255, 0.1);
}

.activity-icon {
  font-size: 1.25rem;
  margin-top: 0.25rem;
}

.activity-content {
  flex: 1;
}

.activity-text {
  color: var(--text-primary);
  margin: 0 0 0.25rem 0;
}

.activity-time {
  font-size: 0.875rem;
  color: var(--text-secondary);
  margin: 0;
}

.no-activity {
  text-align: center;
  padding: 2rem;
  color: var(--text-secondary);
}

/* 快速访问区域 */
.quick-access-section {
  background: var(--bg-card);
  border-radius: 16px;
  padding: 2rem;
  border: 1px solid var(--border-color);
}

.quick-access-buttons {
  display: flex;
  gap: 1rem;
  flex-wrap: wrap;
}

.quick-button {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 1rem 1.5rem;
  background: transparent;
  border: 1px solid var(--border-color);
  border-radius: 12px;
  color: var(--text-primary);
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 0.875rem;
  font-weight: 500;
}

.quick-button:hover {
  border-color: var(--accent-color);
  background: rgba(85, 136, 255, 0.1);
}

.button-icon {
  font-size: 1.25rem;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .current-stats {
    flex-direction: column;
  }
  
  .stat-item {
    justify-content: space-between;
  }
  
  .quick-access-buttons {
    flex-direction: column;
  }
  
  .quick-button {
    justify-content: center;
  }
}

/* 推荐事件预览 */
.recommended-events-preview {
  margin: 1rem 0;
}

.recommended-event-item {
  background-color: rgba(255, 255, 255, 0.05);
  padding: 0.8rem;
  border-radius: 6px;
  margin-bottom: 0.5rem;
}

.recommended-event-item:last-child {
  margin-bottom: 0;
}

.event-date {
  font-size: 0.8rem;
  color: #4a9eff;
  margin-bottom: 0.3rem;
}

.event-title {
  font-size: 0.9rem;
  font-weight: 500;
}

.no-recommendations {
  margin: 1rem 0;
  font-size: 0.9rem;
  color: rgba(255, 255, 255, 0.6);
}
</style>